package com.dingreading.cloud.soms.controller;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.KitUtil;
import com.dingreading.cloud.common.util.PageDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.dingreading.cloud.soms.dto.ReceiptRegisterDto;
import com.dingreading.cloud.soms.entity.ReceiptRegister;
import com.dingreading.cloud.soms.entity.ReceiptRegisterImg;
import com.dingreading.cloud.soms.service.CmordersService;
import com.dingreading.cloud.soms.service.CmpaypicsService;
import com.dingreading.cloud.soms.service.ReceiptRegisterImgService;
import com.dingreading.cloud.soms.service.ReceiptRegisterService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/front/agencyReceiptRegister")
@Api(tags = "门店收款登记管理")
public class ReceiptRegisterController {

    @Resource
    private ReceiptRegisterService receiptRegisterService;
    @Resource
    private ReceiptRegisterImgService receiptRegisterImgService;
    @Resource
    private CmordersService cmordersService;
    @Resource
    private CmpaypicsService cmpaypicsService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "付款开始日期") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "付款结束日期") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(value = "课程类型名称") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "状态 0.未绑定 1.已绑定") @RequestParam(value = "enabled", required = false) Integer enabled
    ) {
        Page<ReceiptRegisterDto> page = receiptRegisterService.pageList(
                pageUtil, storeUid, keyword, enabled, beginDate, endDate
        );

        PageDto<ReceiptRegisterDto> data = new PageDto<>();
        data.setTotal(page.getTotalRow());
        data.setList(page.getRecords());
        return R.ok(data);
    }

    @ApiOperation(value = "获取信息")
    @PostMapping(value = "/get", produces = "application/json; charset=UTF-8")
    public R<Object> get(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "uid") @RequestParam(value = "uid") String uid
    ) {
        ReceiptRegisterDto r = receiptRegisterService.dtoGetByUid(storeUid, uid);
        return R.ok(r);
    }

    @ApiOperation(value = "删除")
    @PostMapping(value = "/delete", produces = "application/json; charset=UTF-8")
    public R<Object> delete(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "uid") @RequestParam(value = "uid") String uid
    ) {
        ReceiptRegister data = receiptRegisterService.getByUid(storeUid, uid);
        if (data == null)
            return R.fail("未查询到信息");
        if (data.getStatus().equals(1))
            return R.fail("已绑定订单，不能操作");

        int l = receiptRegisterService.deleteByUid(uid);
        if (l <= 0) {
            return R.failDel();
        }
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "添加/修改")
    @PostMapping(value = "/add", produces = "application/json; charset=UTF-8")
    public R<Object> add(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "uid") @RequestParam(value = "uid", required = false) String uid,
            @ApiParam(value = "付款人名称") @RequestParam(value = "userName") String userName,
            @ApiParam(value = "付款金额") @RequestParam(value = "amount") Double amount,
            @ApiParam(value = "付款方式") @RequestParam(value = "payment") String payment,
            @ApiParam(value = "付款日期") @RequestParam(value = "payDate", required = false) String payDate,
            @ApiParam(value = "客户地址") @RequestParam(value = "address", required = false) String address,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(value = "收款类型 1.定金 2.其他") @RequestParam(value = "type") Integer type,
            @ApiParam(value = "付款图片集合 [{id:0,url:''}]") @RequestBody(required = false) List<ReceiptRegisterImg> payimgList
    ) throws Exception {
        userName = StringUtils.deleteWhitespace(userName);
        if (StringUtils.isBlank(userName))
            return R.fail("请填写付款人名称");
        if (amount == null || amount <= 0)
            return R.fail("请填写正确的付款金额");
        if (StringUtils.isBlank(payment))
            return R.fail("请选择付款方式");
        if (StringUtils.isBlank(payDate))
            return R.fail("请选择付款日期");
        if (type == null || type <= 0)
            return R.fail("请选择收款类型");
        if (CollectionUtils.isEmpty(payimgList) || payimgList.size() > 5)
            return R.fail("付款图片不能超过5张");

        ReceiptRegister data = null;
        if (StringUtils.isBlank(uid)) {
            data = new ReceiptRegister();
            data.setAddStaffUid(staffUid);
            data.setAddStaffName(staffName);
            data.setCorpUid(corpUid);
            data.setStoreUid(storeUid);
            data.setUid(KitUtil.getUuid());
            data.setStatus(0);
            data.setSaleUid(staffUid);
            data.setSaleName(staffName);
        } else {
            data = receiptRegisterService.getByUid(storeUid, uid);
            if (data == null)
                return R.fail("未查询到信息");
            if (data.getStatus().equals(1))
                return R.fail("已绑定订单，不能操作");
        }
        data.setType(type);
        if (type.equals(1)) {
            data.setTypeName("定金");
        } else if (type.equals(2)) {
            data.setTypeName("其他");
        }
        data.setUserName(userName);
        data.setAmount(amount);
        if (StringUtils.isNotBlank(payDate))
            data.setPayDate(DateUtil.parseDate(payDate));
        data.setPayment(payment);
        data.setAddress(address);
        data.setRemark(remark);
        data.setLastStaffUid(staffUid);
        data.setLastStaffName(staffName);
        receiptRegisterService.saveOrUpdate(data);

        savePayimgList(corpUid, storeUid, data.getUid(), staffUid, staffName, payimgList);
        return R.ok();
    }

    @ApiOperation(value = "获取未绑定的定金列表")
    @PostMapping(value = "/getList", produces = "application/json; charset=UTF-8")
    public R<Object> getList(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "收款登记uid") @RequestParam(value = "receiptUid", required = false) String receiptUid
    ) {
        List<ReceiptRegisterDto> list = receiptRegisterService.unbindList(storeUid, receiptUid);
        return R.ok(list);
    }

    @ApiOperation(value = "解除订单绑定的收款登记")
    @PostMapping(value = "/unbindOrderReceipt", produces = "application/json; charset=UTF-8")
    public R<Object> unbindOrderReceipt(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "订单号") @RequestParam(value = "orderCode") String orderCode,
            @ApiParam(value = "收款登记uid") @RequestParam(value = "receiptUid") String receiptUid
    ) {
        boolean b = receiptRegisterService.unbindReceipt(storeUid, orderCode, receiptUid, staffUid, staffName);
        if (!b)
            return R.fail("解除收款登记失败");

        receiptRegisterImgService.unbindReceipt(storeUid, orderCode, receiptUid, staffUid, staffName);

        cmordersService.unbindReceipt(storeUid, orderCode, receiptUid);
        cmpaypicsService.unbindReceipt(storeUid, orderCode, receiptUid);
        return R.ok();
    }


    /**
     * 保存或编辑付款图片
     */
    private void savePayimgList(
            String corpUid, String storeUid, String receiptUid, String staffUid, String staffName, List<ReceiptRegisterImg> payimgList
    ) {
        // 付款图片
        if (CollectionUtils.isNotEmpty(payimgList)) {
            List<Long> ids = new ArrayList<>();
            for (ReceiptRegisterImg payimg : payimgList) {
                if (payimg.getId() == null || payimg.getId() <= 0) {
                    payimg.setCorpUid(corpUid);
                    payimg.setStoreUid(storeUid);
                    payimg.setReceiptUid(receiptUid);
                    payimg.setAddStaffUid(staffUid);
                    payimg.setAddStaffName(staffName);
                } else {
                    ids.add(payimg.getId());
                }
            }
            // 先删除不要的图片
            List<String> urlList = receiptRegisterImgService.urlListByReceiptUidAndIdsNotIn(storeUid, receiptUid, ids);
            if (CollectionUtils.isNotEmpty(urlList)) {
                int i = receiptRegisterImgService.deleteByReceiptUidNotIn(storeUid, receiptUid, ids);
            }
            receiptRegisterImgService.saveOrUpdateBatch(payimgList);
        } else {
            // 删除全部
            List<String> urlList = receiptRegisterImgService.urlListByReceiptUid(storeUid, receiptUid);
            if (CollectionUtils.isNotEmpty(urlList)) {
                int i = receiptRegisterImgService.deleteByReceiptUid(storeUid, receiptUid);
            }
        }
    }


}
